/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.insurance.cis.views;

import com.insurance.cis.controllers.EmployeeController;
import com.insurance.cis.daos.EmployeeDao;
import com.insurance.cis.daos.GroupDao;
import com.insurance.cis.models.Employee;
import com.insurance.cis.models.Group;
import com.insurance.cis.scos.EmployeeSearchCondition;
import com.insurance.cis.utils.CisConstants;
import com.insurance.cis.utils.MessageDialogUtils;
import com.insurance.cis.utils.Utils;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JOptionPane;
import javax.swing.JRadioButton;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author TruongLQ
 */
public class EmployeeManagementJPanelView extends javax.swing.JPanel {

    DefaultTableModel dtm;
    EmployeeDao employeeDao = new EmployeeDao();
    EmployeeController controller = new EmployeeController(this);
    GroupDao groupDao =new GroupDao();
    final MainJFrameView mainJFrame;
    
    /**
     * Creates new form EmployeeManagementJPanelView
     */
    public EmployeeManagementJPanelView(javax.swing.JFrame jFrame) {
        initComponents();
        mainJFrame = (MainJFrameView) jFrame;
        loadGroups();
        loadTableMetaData();
    }

    private void loadTableMetaData() {
        Vector colHeader = new Vector(10);
        colHeader.add("Employee ID");
        colHeader.add("Employee Name");
        colHeader.add("Username");
        colHeader.add("Gender");
        colHeader.add("Birthday");
        colHeader.add("Group");
        dtm = new DefaultTableModel(colHeader, 0) {
            @Override
            public boolean isCellEditable(int row, int column) {
                return false;
            }
        };
        tblEmployeeResult.setModel(dtm);
    }
    
    private void loadGroups() {
        Vector<Group> groups = groupDao.getAllGroups();
        groups.add(0, new Group(null, "Select a group"));
        cbxGroup.setModel(new DefaultComboBoxModel(groups));
    }
    
    public void clearAllTextFields() {
        btnResetActionPerformed(null);
        dtm.getDataVector().clear();
    }
    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        btnGenderGroup = new javax.swing.ButtonGroup();
        btnUpdate = new javax.swing.JButton();
        btnCreate = new javax.swing.JButton();
        ScrollProductList = new javax.swing.JScrollPane();
        tblEmployeeResult = new javax.swing.JTable();
        btnClose = new javax.swing.JButton();
        btnDelete = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtEmployeeID = new javax.swing.JTextField();
        txtEmployeeName = new javax.swing.JTextField();
        txtUsername = new javax.swing.JTextField();
        jLabel5 = new javax.swing.JLabel();
        rbtnMale = new javax.swing.JRadioButton();
        rbtnFemale = new javax.swing.JRadioButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        txtEmployeeDob = new javax.swing.JTextField();
        cbxGroup = new javax.swing.JComboBox();
        btnSearch = new javax.swing.JButton();
        btnReset = new javax.swing.JButton();

        btnUpdate.setText("Update");
        btnUpdate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnUpdateActionPerformed(evt);
            }
        });

        btnCreate.setText("Create");
        btnCreate.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCreateActionPerformed(evt);
            }
        });

        ScrollProductList.setBorder(null);

        tblEmployeeResult.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        tblEmployeeResult.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                tblEmployeeResultMouseClicked(evt);
            }
        });
        ScrollProductList.setViewportView(tblEmployeeResult);

        btnClose.setText("Close");
        btnClose.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCloseActionPerformed(evt);
            }
        });

        btnDelete.setText("Delete");
        btnDelete.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnDeleteActionPerformed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel1.setText("Search an existing employee");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(javax.swing.border.EtchedBorder.RAISED), "Search criteria", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 12))); // NOI18N

        jLabel2.setText("Employee ID");

        jLabel3.setText("Employee Name");

        jLabel4.setText("Username");

        jLabel5.setText("Gender");

        btnGenderGroup.add(rbtnMale);
        rbtnMale.setText("Male");

        btnGenderGroup.add(rbtnFemale);
        rbtnFemale.setText("Female");

        jLabel6.setText("Birthday");

        jLabel7.setText("Group");

        btnSearch.setText("Search");
        btnSearch.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchActionPerformed(evt);
            }
        });

        btnReset.setText("Reset");
        btnReset.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnResetActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btnSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 99, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(45, 45, 45))
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGap(46, 46, 46)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4))
                .addGap(28, 28, 28)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(txtUsername)
                    .addComponent(txtEmployeeName)
                    .addComponent(txtEmployeeID, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(49, 49, 49)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel5)
                    .addComponent(jLabel6)
                    .addComponent(jLabel7))
                .addGap(30, 30, 30)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(rbtnMale)
                        .addGap(18, 18, 18)
                        .addComponent(rbtnFemale))
                    .addComponent(txtEmployeeDob)
                    .addComponent(cbxGroup, javax.swing.GroupLayout.PREFERRED_SIZE, 157, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(179, Short.MAX_VALUE))
        );

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel2, jLabel3, jLabel4});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel5, jLabel6, jLabel7});

        jPanel1Layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnReset, btnSearch});

        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(txtEmployeeID, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel5)
                    .addComponent(rbtnMale)
                    .addComponent(rbtnFemale))
                .addGap(6, 6, 6)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtEmployeeName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3)
                    .addComponent(jLabel6)
                    .addComponent(txtEmployeeDob, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel4)
                    .addComponent(jLabel7)
                    .addComponent(cbxGroup, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnSearch)
                    .addComponent(btnReset))
                .addContainerGap(17, Short.MAX_VALUE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(53, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(btnCreate)
                            .addGap(18, 18, 18)
                            .addComponent(btnUpdate)
                            .addGap(18, 18, 18)
                            .addComponent(btnDelete)
                            .addGap(18, 18, 18)
                            .addComponent(btnClose, javax.swing.GroupLayout.PREFERRED_SIZE, 104, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(ScrollProductList)))
                .addGap(53, 53, 53))
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btnClose, btnCreate, btnDelete, btnUpdate});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addComponent(ScrollProductList, javax.swing.GroupLayout.PREFERRED_SIZE, 202, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnCreate)
                    .addComponent(btnUpdate)
                    .addComponent(btnDelete)
                    .addComponent(btnClose))
                .addGap(29, 29, 29))
        );
    }// </editor-fold>//GEN-END:initComponents

    private void btnUpdateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnUpdateActionPerformed
        int row = tblEmployeeResult.getSelectedRow();
        if (row <0 || row >= tblEmployeeResult.getRowCount()) {
            MessageDialogUtils.dialogError(this, "You must choose one item to update!");
            return;
        }
        
        Employee chosenEmployee = employeeDao.getEmployee((String)dtm.getValueAt(row, 0));
        EmployeeJDialogUpdateView employeeJDialogUpdateView = 
                new EmployeeJDialogUpdateView(mainJFrame, true, chosenEmployee);
        employeeJDialogUpdateView.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        employeeJDialogUpdateView.setVisible(true);
    }//GEN-LAST:event_btnUpdateActionPerformed

    private void btnCreateActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCreateActionPerformed
        EmployeeJDialogCreationView dialog = new EmployeeJDialogCreationView(
                mainJFrame, true);
        dialog.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
        dialog.setVisible(true);
    }//GEN-LAST:event_btnCreateActionPerformed

    private void tblEmployeeResultMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tblEmployeeResultMouseClicked
        //mouseClickTable();
    }//GEN-LAST:event_tblEmployeeResultMouseClicked

    private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchActionPerformed
        EmployeeSearchCondition sco = controller.validateSearchConditions();
        if (sco == null) {
            return;
        }
        List<Employee> employees = employeeDao.searchEmployees(sco);
        if (!employees.isEmpty()) {
            loadResults(employees);
        } else {
            MessageDialogUtils.dialogMessage(this, "No employees found");
            dtm.getDataVector().clear();
            tblEmployeeResult.updateUI();
        }
    }//GEN-LAST:event_btnSearchActionPerformed

    private void loadResults(List<Employee> employees) {
        dtm.getDataVector().clear();
        for (Employee employee : employees) {
            dtm.addRow(new Object[]{
                employee.getCode(),
                employee.getName(),
                employee.getUserName(),
                employee.getGender(),
                (employee.getDob()!=null)?Utils.convertDateToString(employee.getDob(), CisConstants.DATE_DD_MM_YYYY):null,
                employee.getGroup().getGroupDesc()
            });
        }
    }
    
    private void btnCloseActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCloseActionPerformed
        this.mainJFrame.dispose();
    }//GEN-LAST:event_btnCloseActionPerformed

    private void btnDeleteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnDeleteActionPerformed
        int row = tblEmployeeResult.getSelectedRow();
        if (row <0 || row >= tblEmployeeResult.getRowCount()) {
            MessageDialogUtils.dialogError(this, "You must choose one item to delete!");
            return;
        }
        int okToDelete = MessageDialogUtils.dialogQuestion(
                this, "Do you want to delete this selected employee?", 
                JOptionPane.YES_NO_OPTION); 
        if (okToDelete != JOptionPane.NO_OPTION) {
            try {
                employeeDao.deleteEmployee((String)dtm.getValueAt(row, 0));
                MessageDialogUtils.dialogMessage(this, "Delete employee successful");
                refreshSearchResult();
            } catch (Exception ex) {
                MessageDialogUtils.dialogMessage(this, "Error while deleting employee");
            }
            
        }
    }//GEN-LAST:event_btnDeleteActionPerformed

    public void refreshSearchResult() {
        btnSearchActionPerformed(null);
        tblEmployeeResult.updateUI();
    }
    
    private void btnResetActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnResetActionPerformed
        txtEmployeeDob.setText("");
        txtEmployeeID.setText("");
        txtEmployeeName.setText("");
        txtUsername.setText("");
        btnGenderGroup.clearSelection();
        cbxGroup.setSelectedIndex(0);
    }//GEN-LAST:event_btnResetActionPerformed
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane ScrollProductList;
    private javax.swing.JButton btnClose;
    private javax.swing.JButton btnCreate;
    private javax.swing.JButton btnDelete;
    private javax.swing.ButtonGroup btnGenderGroup;
    private javax.swing.JButton btnReset;
    private javax.swing.JButton btnSearch;
    private javax.swing.JButton btnUpdate;
    private javax.swing.JComboBox cbxGroup;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JRadioButton rbtnFemale;
    private javax.swing.JRadioButton rbtnMale;
    private javax.swing.JTable tblEmployeeResult;
    private javax.swing.JTextField txtEmployeeDob;
    private javax.swing.JTextField txtEmployeeID;
    private javax.swing.JTextField txtEmployeeName;
    private javax.swing.JTextField txtUsername;
    // End of variables declaration//GEN-END:variables

    public JComboBox getCbxGroup() {
        return cbxGroup;
    }

    public JRadioButton getRbtnFemale() {
        return rbtnFemale;
    }

    public JRadioButton getRbtnMale() {
        return rbtnMale;
    }

    public JTextField getTxtEmployeeDob() {
        return txtEmployeeDob;
    }

    public JTextField getTxtEmployeeID() {
        return txtEmployeeID;
    }

    public JTextField getTxtEmployeeName() {
        return txtEmployeeName;
    }

    public JTextField getTxtUsername() {
        return txtUsername;
    }

    
}
